package cn.daniellee.plugin.rb.listener;

import cn.daniellee.plugin.rb.ResidenceBungee;
import cn.daniellee.plugin.rb.core.BungeeCore;
import com.google.common.io.ByteArrayDataInput;
import com.google.common.io.ByteStreams;
import org.bukkit.entity.Player;
import org.bukkit.plugin.messaging.PluginMessageListener;

import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.util.Arrays;

public class BungeeListener implements PluginMessageListener {

	@Override
	public void onPluginMessageReceived(String s, Player player, byte[] bytes) {
		ByteArrayDataInput in = ByteStreams.newDataInput(bytes);
		String subChannel = in.readUTF();
		if ("GetServer".equals(subChannel)) {
			String serverName = in.readUTF();
			BungeeCore.serverName = serverName;
			ResidenceBungee.getInstance().getLogger().info("[ResidenceBungee]Successfully fetched the server name: " + serverName);
			// 向所有服务器发送地皮列表
			BungeeCore.sendResListMessage("ALL");
			// 向所有服务器请求地皮列表
			BungeeCore.sendResRequestMessage();
		} else if ("ResidenceBungee".equals(subChannel)) {
			short length = in.readShort();
			byte[] msgBytes = new byte[length];
			in.readFully(msgBytes);
			DataInputStream msgIn = new DataInputStream(new ByteArrayInputStream(msgBytes));
			try {
				String msg = msgIn.readUTF();
				switch (msg) {
					case "ResList":
						String serverName = msgIn.readUTF();
						if (!"Invalid".equals(serverName)) {
							String resList = msgIn.readUTF();
							// 将领地列表写入Map
							Arrays.stream(resList.split(",")).forEach(item -> BungeeCore.residenceMap.put(item, serverName));
							ResidenceBungee.getInstance().getLogger().info("Server: " + serverName + ", Residences: " +  resList);
						}
						break;
					case "ResRequest":
						String targetServer = msgIn.readUTF();
						// 向目标服务器发送领地列表
						BungeeCore.sendResListMessage(targetServer);
						break;
					case "Teleport":
						String playerName = msgIn.readUTF();
						String buildingId = msgIn.readUTF();
						BungeeCore.teleportMap.put(playerName, buildingId);
						break;
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}
